<template>
  <div class="chart-container" ref="chartContainer">
    <svg ref="chartSvg"></svg>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as d3 from 'd3'

const props = defineProps({
  data: {
    type: Array,
    default: () => []
  },
  height: {
    type: String,
    default: '400px'
  },
  currentDevice: {
    type: Object,
    default: () => null
  },
  xRange: {
    type: Array,
    default: () => []
  }
})

const chartContainer = ref(null)
const chartSvg = ref(null)
let chart = null

// 清除图表
const clearChart = () => {
  if (chartSvg.value) {
    d3.select(chartSvg.value).selectAll('*').remove()
  }
}

// 创建图表
const createChart = () => {
  // console.log('D3ChartGraph - 创建图表，数据:', props.data)
  // console.log('D3ChartGraph - xRange:', props.xRange)
  
  if (!chartContainer.value) {
    // console.warn('D3ChartGraph - 图表容器不存在')
    return
  }
  
  if (!props.data || !props.data.length) {
    // console.warn('D3ChartGraph - 数据为空')
    return
  }

  clearChart()

  // 获取容器尺寸
  const containerWidth = chartContainer.value.clientWidth
  const containerHeight = parseInt(props.height)

  // 设置 SVG 尺寸
  const svg = d3.select(chartSvg.value)
    .attr('width', containerWidth)
    .attr('height', containerHeight)

  // 设置边距
  const margin = { top: 20, right: 20, bottom: 30, left: 40 }
  const width = containerWidth - margin.left - margin.right
  const height = containerHeight - margin.top - margin.bottom

  // 创建绘图区域
  const g = svg.append('g')
    .attr('transform', `translate(${margin.left},${margin.top})`)

  // 设置比例尺
  const x = d3.scaleLinear()
    .domain([0, 6]) // 修改domain起始值为0
    .range([0, width])

  const y = d3.scaleLinear()
    .domain([0, 100]) // 设置Y轴最大值为100
    .range([height, 0])

  // 创建坐标轴，设置X轴刻度为7个点（0到6）
  const xAxis = d3.axisBottom(x)
    .ticks(7)
    .tickValues([0, 1, 2, 3, 4, 5, 6]) // 修改tickValues包含0
    .tickFormat(d3.format('d'))
  const yAxis = d3.axisLeft(y)

  // 添加坐标轴
  g.append('g')
    .attr('transform', `translate(0,${height})`)
    .call(xAxis)
    .append('text')
    .attr('fill', '#000')
    .attr('x', width)
    .attr('y', -6)
    .attr('text-anchor', 'end')
    .text('位移 (mm)')

  g.append('g')
    .call(yAxis)
    .append('text')
    .attr('fill', '#000')
    .attr('transform', 'rotate(-90)')
    .attr('y', 6)
    .attr('dy', '0.71em')
    .attr('text-anchor', 'end')
    .text('载荷 (kN)')

  // 创建折线生成器
  const line = d3.line()
    .x(d => x(d[0]))
    .y(d => y(d[1]))
    .curve(d3.curveMonotoneX)

  // 不再使用线性渐变，而是将数据分为两部分，分别绘制红色和蓝色的线
  const halfIndex = Math.floor(props.data.length / 2);
  const firstHalfData = props.data.slice(0, halfIndex);
  const secondHalfData = props.data.slice(halfIndex);
  
  // 绘制前半部分折线（红色）
  g.append('path')
    .datum(firstHalfData)
    .attr('fill', 'none')
    .attr('stroke', '#F56C6C')
    .attr('stroke-width', 2)
    .attr('d', line);
    
  // 绘制后半部分折线（蓝色）
  g.append('path')
    .datum(secondHalfData)
    .attr('fill', 'none')
    .attr('stroke', '#2196F3')
    .attr('stroke-width', 2)
    .attr('d', line)

  // 绘制散点
  g.selectAll('circle')
    .data(props.data)
    .enter()
    .append('circle')
    .attr('cx', d => x(d[0]))
    .attr('cy', d => y(d[1]))
    .attr('r', 3)
    .attr('fill', (d, i) => i < props.data.length / 2 ? '#F56C6C' : '#2196F3') // 前半部分红色，后半部分蓝色
    .attr('stroke', '#fff')
    .attr('stroke-width', 1)

  // 添加网格线
  g.append('g')
    .attr('class', 'grid')
    .attr('opacity', 0.1)
    .call(d3.axisBottom(x)
      .tickSize(height)
      .tickFormat(''))

  g.append('g')
    .attr('class', 'grid')
    .attr('opacity', 0.1)
    .call(d3.axisLeft(y)
      .tickSize(-width)
      .tickFormat(''))
}

// 监听数据变化
watch(() => props.data, () => {
  createChart()
}, { deep: true })

// 监听窗口大小变化
const handleResize = () => {
  createChart()
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
  createChart()
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  clearChart()
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-sizing: border-box;
}

svg {
  display: block;
  width: 100%;
}

:deep(.grid line) {
  stroke: #000;
}

:deep(.grid path) {
  stroke-width: 0;
}
</style>
